<?php

namespace app\common\library;

use think\Env;
use think\Exception;
use Carbon\Carbon;
use app\admin\model\user\Extend as UserExtendModel;
use app\admin\model\user\Credits as UserCreditsModel;
use app\admin\model\Reserve as ReserveModel;
use app\admin\model\Setting as SettingModel;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

class Credit
{
    
    protected $_calcStartTime = 0;
    protected $perSeconds = 60 * 30;

    public function __construct()
    {
        $this->_calcStartTime = Env::get('common.calc_starttime');
    }

    public function calcCreditDaemon()
    {
        // 获取系统设置的每半小时的信用分
        $addCreditScore = SettingModel::getSingleSetting('add_credit');
        if (!$addCreditScore) {
            echo 'no found add credit setting';
            exit;
        }

        $curTime = Carbon::now()->toDateTimeString(); 
        // 查找re_status = 1, endtime > curTime,并且yunding_errno <> 1的记录
        // createtime > calcStartTime
        $wheres = [
            're_status' => '1',
            'endtime' => ['<', $curTime],
            'has_dealed_credit' => ['<>', 1],
            'createtime' => ['>', $this->_calcStartTime],
        ];
        $reserves  = ReserveModel::where($wheres)->select();
        foreach ($reserves as $reserve) {
            $starttime = strtotime($reserve->starttime); 
            $endtime = strtotime($reserve->endtime) + 60;
            $userId = $reserve->user_id;

            $diffTime = $endtime - $starttime;
            $diffUnit = $diffTime / $this->perSeconds;
            $addScore = $diffUnit * $addCreditScore;
            
            $ret = $this->addCredit($userId, $addScore);
            if ($ret === 0) {
                // 更新对应记录状态
                $reserve->has_dealed_credit = 1;
                $reserve->save();
                Log::write('增加信用分成功 => 用户Id:' . $userId . ',预定id:' . $reserve->id .  '，变动的信用分:' . $addScore, 'info');
            } else {
                Log::write('增加信用分失败 => 用户Id:' . $userId . ',预定id:' . $reserve->id, 'error');
            }
        }
    }

    public function addCredit($userId, $creditScore)
    {
        $ret = 0;
        $userExtend = UserExtendModel::where('user_id', $userId)->find();
        if ($userExtend) {
            Db::startTrans();
            try {
                $before = $userExtend->credit_score;
                $after = $userExtend->credit_score + $creditScore;
                $userExtend->credit_score = $after;
                $userExtend->save();
                // 增加日志
                $credits = new UserCreditsModel();
                $credits->user_id = $userId;
                $credits->credit_score = $creditScore;
                $credits->before = $before;
                $credits->after = $after;
                $credits->type = 1;
                $credits->memo = '守约增加';
                $credits->createtime = time();
                $credits->save();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                Log::write('错误:' . $e->getMessage(), 'error');
                $ret = 1;
            } catch (Exception $e) {
                Db::rollback();
                Log::write('错误:' . $e->getMessage(), 'error');
                $ret = 1;
            }
        }

        return $ret; 
    }

    public function declineCredit($userId, $creditScore)
    {
        $ret = 0;
        if ($creditScore === 0) {
            return $ret;
        }
        $userExtend = UserExtendModel::where('user_id', $userId)->find();
        if ($userExtend) {
            Db::startTrans();
            try {
                $before = $userExtend->credit_score;
                $after = $userExtend->credit_score - $creditScore;
                if ($after < 0) {
                    throw new \Exception('信用分不足够');
                }
                $userExtend->credit_score = $after;
                $userExtend->save();
                // 增加日志
                $credits = new UserCreditsModel();
                $credits->user_id = $userId;
                $credits->credit_score = -$creditScore;
                $credits->before = $before;
                $credits->after = $after;
                $credits->type = 2;
                $credits->memo = '取消预约扣除';
                $credits->createtime = time();
                $credits->save();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                Log::write('错误:' . $e->getMessage(), 'error');
                $ret = 1;
            } catch (Exception $e) {
                Db::rollback();
                Log::write('错误:' . $e->getMessage(), 'error');
                $ret = 1;
            }
        }

        return $ret; 
    
    }

    public function getLogs($userId)
    {
        $logs = UserCreditsModel::where('user_id', $userId)->order('createtime desc')->paginate(request()->param('list_rows', 5))->toArray();
        return $logs;
    }
}
